<template>
  <div class="homework">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>作业列表</span>
        </div>
      </template>
      <el-input style="width: 300px" @clear="searchOrder" clearable v-model="searchForm.name" placeholder="请输入作业名称"
        class="input-with-select">
        <template #append>
          <el-button icon="Search" @click="searchOrder" />
        </template>
      </el-input>

      <span style="font-size: 15px; margin-left: 20px"> 选择年份：</span>
      <el-select v-model="searchForm.year" placeholder="Select" style="width: 140px">
        <el-option v-for="item in years" :key="item.year" :value="item.year" />
      </el-select>
      <span style="font-size: 15px; margin-left: 20px"> 月份：</span>
      <el-select v-model="searchForm.month" placeholder="Select" style="width: 80px" @change="searchOrder">
        <el-option v-for="item in 12" :key="item" :value="item" :label="`${item}月`" />
      </el-select>
      <el-button type="primary" class="add" @click="add"><el-icon>
          <UploadFilled />
        </el-icon>&nbsp;上传作业</el-button>
      <el-table :data="tableData" border style="width: 100%; margin-top: 20px" :row-class-name="tableRowClassName"
        class="my-table">
        <el-table-column prop="" label="序号" width="80">
          <template #default="scope">
            <el-tag type="info">{{ scope.$index + 1 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="homework_name" label="作业名称" />
        <el-table-column prop="author" label="作者" />
        <el-table-column prop="type" label="类型" />
        <el-table-column prop="work_date" label="时间" />
        <el-table-column prop="notes" label="备注" />
        <el-table-column prop="files" label="文件">
          <template #default="scope">
            <div class="demo-file-preview">
              <template v-if="scope.row.imgList.length > 0">
                <!-- 图片预览 -->
                <el-image style="width: 100px; height: 100px" :src="`${baseURL}/${scope.row.imgList[0]}`" :zoom-rate="1.2"
                  :max-scale="7" :min-scale="0.2" :preview-src-list="scope.row.imgList.map((f) => `${baseURL}/${f}`)
                    " :initial-index="index" :crossorigin="null" fit="cover" />
              </template>
              <template v-if="scope.row.videoList.length > 0">
                <el-button style="margin:10px" v-for="(v, index) in scope.row.videoList"
                  @click="showVideo(`${baseURL}/${scope.row.videoList[index]}`)">播放视频{{ index + 1 }}</el-button>
              </template>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button size="small" @click="editOrder(scope.row.id)" v-show="username == scope.row.author">编辑</el-button>

            <el-button type="danger" size="small" @click="deleteOrder(scope.row.id)"
              v-show="username == scope.row.author">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination style="margin-top: 20px" :current-page="searchForm.current" :page-size="searchForm.size"
        :page-sizes="[20, 50, 100]" layout="->,total, sizes, prev, pager, next, jumper" :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 弹窗组件，用于播放视频 -->
    <el-dialog v-model="dialogVisible" :before-close="handleClose" class="videoDialog" :width="'auto'">
      <div class="videoContainer">
        <video controls v-if="currentVideoSrc" ref="videoPlayer" @loadedmetadata="adjustVideoSize">
          <source :src="currentVideoSrc" />
          您的浏览器不支持视频播放。
        </video>
      </div>
    </el-dialog>

  </div>
</template>

<script setup>
import { reactive, ref, onMounted,nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import workApi from '../../api/work'
import homeworkApi from '../../api/homework'
import { useRouter } from 'vue-router'
const router = useRouter()

const tableData = ref([])
let total = ref(0)
const years = ref()
const username = sessionStorage.getItem('username') //日志需要
// 获取全局变量
const baseURL = window.globalConfig.baseURL

const dialogVisible = ref(false)
const currentVideoSrc = ref()

// 搜索条件
const searchForm = reactive({
  current: 1,
  size: 20,
  name: '',
  year: '',
})

onMounted(async () => {
  const yearRes = await workApi.getDistinctYears()
  years.value = yearRes.data
  console.log(years.value)
  //默认今年
  const currentYear = new Date().getFullYear()
  searchForm.year = currentYear

  //默认当月
  const currentMonth = new Date().getMonth() + 1
  searchForm.month = currentMonth

  //请求数据
  getHomeworks()
})

// 获取数据列表
const getHomeworks = async () => {
  const res = await homeworkApi.getHomeworks(searchForm);
  console.log(res);
  // 处理work_date，只取年月日，并区分文件类型
  const processedData = res.data.rows.map((order) => {
    const { work_date, fileList, ...rest } = order;
    const imgList = [];
    const videoList = [];

    // 假设fileList是一个包含文件URL的数组
    fileList.forEach((file) => {
      // 这里简单地用文件扩展名来判断文件类型
      const ext = file.split('.').pop().toLowerCase();
      if (['jpg', 'jpeg', 'png', 'gif'].includes(ext)) {
        imgList.push(file);
      } else if (['mp4', 'avi', 'mov'].includes(ext)) {
        videoList.push(file);
      }
    });

    return {
      ...rest,
      work_date: new Date(new Date(work_date).getTime() + 8 * 60 * 60 * 1000)
        .toISOString()
        .split('T')[0], // 转换成北京时间
      imgList,
      videoList,
    };
  });

  tableData.value = Object.assign([], processedData);
  total.value = res.data.totalCount;
}


const handleSizeChange = (size) => {
  searchForm.size = size
  getHomeworks()
}
const handleCurrentChange = (current) => {
  searchForm.current = current
  getHomeworks()
}
const searchOrder = () => {
  searchForm.current = 1
  getHomeworks()
}

const add = async () => {
  router.push({
    path: '/homework_list/upload',
  })
}

const editOrder = async (id) => {
  router.push({
    path: '/homework_list/upload',
    query: { id: id },
  })
}

// 删除项目
const deleteOrder = (id) => {
  ElMessageBox.confirm('确定要删除该项目吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const username = sessionStorage.getItem('username')
      const res = await homeworkApi.delHomework({ id: id, username: username })
      if (res.data.success) {
        ElMessage.success('删除成功')
        getHomeworks()
      } else {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const showVideo = async (url) => {
  dialogVisible.value = true
  currentVideoSrc.value = url
  //这里让视频开始播放
  await nextTick(); // Ensure DOM is updated
  videoPlayer.value.play(); // Start playing the video
}

const handleClose = () => {
  currentVideoSrc.value = ''
  dialogVisible.value = false
  videoPlayer.value.load(); // Start playing the video
}

const videoPlayer = ref(null);
const adjustVideoSize = () => {
  const video = videoPlayer.value;
  if (video.videoWidth > video.videoHeight) {
    // Horizontal video
    video.style.width = '80%';
    video.style.height = 'auto';

  } else {
    // Vertical video
    video.style.width = '60%';
    video.style.height = 'auto';
  }
}
</script>

<style scoped>
.homework .add {
  float: right;
  margin-bottom: 20px;
}

.homework .el-table .cell {
  text-align: center;
  line-height: 100%;
}

/* .input-with-select{
  margin-left:100px;
} */
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-tag.ml-2 {
  margin: 4px;
  cursor: pointer;
}

.el-table thead tr {
  font-size: 17px;
}

.el-progress-circle {
  width: 50px !important;
  height: 50px !important;
}

.el-progress__text span {
  font-size: 13px;
}

.el-table {
  --el-table-index: none;
}

.el-dialog__header {
  margin-right: 0;
  padding: 0;
}

.videoDialog {
  width: 50%;
}

.videoDialog {
  display: flex;
  justify-content: center;
  align-items: center;
}

.videoContainer {
  display: flex;
  justify-content: center;
  align-items: center;
  max-width: 100%;
  max-height: 100%;
  overflow: hidden;
}

.videoContainer video {
  max-width: 100%;
  display: block;
}
</style>
